package com.wsc.personalblog.common;
import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MsgConsumer {

    //application.properties中已配置的值
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired

    /**
     * 消费验证码，发送给用户
     * @param message
     */
    @RabbitListener(queues = "normal_Exchange")
    public void consumerMsg(Message message){
        String msg = new String(message.getBody());
        Map<String,Object> map = JSON.parseObject(msg, Map.class);//将json格式转换为Map格式
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        String code = (String)map.get("code");
        String email = (String)map.get("email");
        mailMessage.setSubject("验证码邮件");//主题
        mailMessage.setText("您收到的验证码是："+code+"\t请五分钟内完成操作");//内容
        mailMessage.setTo(email);//发给谁
        mailMessage.setFrom(from);//你自己的邮箱
        mailSender.send(mailMessage);//发送
    }
}
